package com.sstock.smartstock;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.mobclick.android.MobclickAgent;





import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class RefreshService extends Service {
	
	//Add for startforeground
	private static final Class<?>[] mSetForegroundSignature = new Class[] {
	    boolean.class};
	private static final Class<?>[] mStartForegroundSignature = new Class[] {
	    int.class, Notification.class};
	private static final Class<?>[] mStopForegroundSignature = new Class[] {
	    boolean.class};

	private NotificationManager mNM_fore;
	private Method mSetForeground;
	private Method mStartForeground;
	private Method mStopForeground;
	private Object[] mSetForegroundArgs = new Object[1];
	private Object[] mStartForegroundArgs = new Object[2];
	private Object[] mStopForegroundArgs = new Object[1];
	//Add for startforeground
	
	private String TAG = "RefreshService";
	private final String sHead = "s_";
	
	Calendar calendar = Calendar.getInstance();
	
	private long makeDB;
	private long makeComp;
	private long downloadF;
	private long downloadFL;
	private long dealFile;
	
	
	//test String variable
	private String tempEmpty[] = {"","","",""};
	private static boolean closeThread;
	private String searchUrl = "http://hq.sinajs.cn/list=%s";
	private String searchStock = "http://suggest3.sinajs.cn/suggest/type=11,12&key=%s&name=suggestdata_%s";
	private String urlDownLoad = "http://52apk.net/apps/downloads/stocklist.txt";
	private String file_path = Environment.getExternalStorageDirectory() + "/stocklist/";
	private String dbFile = "/data/data/com.sstock.smartstock/databases/stocklist.db";
	
	public static final String KEY_STOCK_SEARCH = "stock_code_search";
	public static final String KEY_STOCK_NAME= "stock_name";
	public static final String KEY_STOCK_CODE = "stock_code";
	public static final String KEY_STOCK_PINYIN= "stock_pinyin";
	public int STOCKLISTDB_VERSION = 1;
	
	final ArrayList<String> stockSelfSelect = new ArrayList<String>();
	final ArrayList<String> stockSSCode     = new ArrayList<String>();
	final ArrayList<StockDisplay> stockDisplayList = new ArrayList<StockDisplay>();
	final ArrayList<StockSearch> stockSearchList = new ArrayList<StockSearch>();
	public ArrayList<StockSearch> stockListData   = new ArrayList<StockSearch>();
	final ArrayList<StockNeedAnalyze> stockNeedAnalyze = new ArrayList<StockNeedAnalyze> ();
	
	//local variable
	public static String[] filter_note = new String[2];
	public static String[] s_data = new String[6];
	public static String[] filter_data = new String[3];
	
	public HashMap<String,String> stocksimnum= new HashMap<String,String>();
	public HashMap<String,String> stocksimprice = new HashMap<String,String>();
	private int i = 0;
	private static String tempString = "";
	private StockDisplay tempStockDisplay;
	private StockSearch tempStockSearch;
	private StockFormat tempStockFormat;
	private StockNeedAnalyze tempStockNeedAnalyze;
	private boolean startAnalyze;
	
	private boolean analyzeThreadRun = false;
	private Thread analyzeThread;
	public Handler mHandler;

	
	
	//database variable
	StockSelfSelectDB stockDBAdapter;
	StockListDB stockListDB;
	
	//Alarm variable
	private NotificationManager mNM;
	
	private Messenger mMessenger;// = new Messenger(mHandler);
	
	private volatile Messenger cMessenger;
	
	@Override
	public void onCreate() {
		
		//first test the network connect
		testConnect();
		
		Log.v(TAG, "oncreateService");
		mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		
		stockDBAdapter = new StockSelfSelectDB(this);
		
		stockDBAdapter.open();
		
		stockListDB = new StockListDB(this);
		
		if(!FileOperation.isThereTheFile(dbFile))
		{
			stockListDB.open();
		}
		
		updateStockList();
		//This variable cannot define in the Class, 
		//or you must wait until the Process died you can received a new one
		closeThread = false;
		
		startAnalyze = true;
		
		
		setmNM_fore((NotificationManager)getSystemService(NOTIFICATION_SERVICE));
	    try {
	        mStartForeground = getClass().getMethod("startForeground",
	                mStartForegroundSignature);
	        mStopForeground = getClass().getMethod("stopForeground",
	                mStopForegroundSignature);
	    } catch (NoSuchMethodException e) {
	        // Running on an older platform.
	        mStartForeground = mStopForeground = null;
	    }
	    CharSequence text = getText(R.string.foreground_service_started);
	    
	    Notification notification = new Notification(R.drawable.icon, text,
                System.currentTimeMillis());

	    Intent intent = new Intent(this, Home.class);
	    intent.setAction(Intent.ACTION_MAIN);
	    intent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
        		intent, 0);

        notification.setLatestEventInfo(this, "Foreground Service",
        		"Foreground Service Started.", contentIntent);
        // 注意使用  startForeground ，id 为 0 将不会显示 notification
        startForegroundCompat(1, notification);
        Globals.isServiceRunning = false;
		
	}


	@Override
    public void onDestroy() {
        // Cancel the service
		Log.v(TAG, "onDestory");
		closeThread = true;
		startAnalyze = false;
		// close the database
		stockListDB.close();
		stockDBAdapter.close();
		stopForegroundCompat(1);
		Globals.isServiceRunning = false;
		super.onDestroy(); 	
    }
	
	@Override
	public boolean onUnbind(Intent intent) {
		
		Log.v(TAG, "onUnbind");
		mHandler = null;
		return true;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.v(TAG, "onBind");
		testConnect();
		cMessenger = intent.getExtras().getParcelable(Globals.UI_HANDLER_NAME);
		mHandler = new MyHandler(cMessenger);
		mMessenger = new Messenger(mHandler);
		Globals.dataHandler = mMessenger;
    	return mMessenger.getBinder();
	}
	
	@Override
	public void onRebind(Intent intent) {
		
		testConnect();
		Log.v(TAG, "onRebind");
		cMessenger = Globals.uiMessager;
		mHandler = new MyHandler(cMessenger);
		mMessenger = new Messenger(mHandler);
		Globals.dataHandler = mMessenger;
		Message msgOut = Message.obtain();
		msgOut.what = Globals.UIMESSEAGE_CONNECT_OK;
		String listDate = MobclickAgent.getConfigParams(this, "listdate");
		Bundle data = new Bundle();
		data.putString(Globals.UINAME_LISTDATE, listDate);
		Log.v(TAG,"listdate="+listDate);
		msgOut.setData(data);
		mHandler.sendMessage(msgOut);
	}
	
	public class MyHandler extends Handler {	
		Messenger cMessenger;
		public MyHandler(Messenger cMessenger) {
			this.cMessenger = cMessenger;
		}
		public void handleMessage(Message msg)
		{
			switch(msg.what) {
			/**
			 * this case used to analyze which one need alarm
			 */
			case Globals.STOCK_NEED_ANALYZE:
			{
				Log.v(TAG,"received need analyze stock!");
				boolean flag = isOpenMarketDay();
				findNeedAnalyzeArray();
				if(stockNeedAnalyze.size() != 0)
				{
					if(!analyzeThreadRun)
					{
						analyzeThread = new Thread(new Runnable() 
					  	  {
						  	@Override
						  	public void run() {
						  		Log.v(TAG,"start analyze thread!");
						  		Log.v(TAG,String.valueOf(startAnalyze) + " is here for flag!");
						  		while(startAnalyze)
						  		{
						  			for(int index = 0; index < stockNeedAnalyze.size(); index++)
						  			{
						  				String stock = stockNeedAnalyze.get(index).getStockCode();
						  				String rise_price = stockNeedAnalyze.get(index).getStockRisePrice();
						  				float rise = Float.valueOf(rise_price);
						  				String drop_price = stockNeedAnalyze.get(index).getStockRisePrice();
						  				float drop = Float.valueOf(drop_price);
						  				String current_price = stockDBAdapter.getStockCurrentPrice(stock);
						  				float current = Float.valueOf(current_price);
						  				
						  				Log.v(TAG, stock);
						  				if(current >= rise)
						  				{
						  					showNotification(0, stock, rise_price, current_price, "up");
						  					stockDBAdapter.updateNeedAnalyze(stock,"F");
						  					
						  					Message msgneedalarmr = new Message();
						  					msgneedalarmr.what = Globals.STOCK_NEED_ALARM;
						  					sendMessage(msgneedalarmr);
						  					
						  					String tempflag = stockDBAdapter.getNeedAnalyzeFlag(stock);
						  					
						  					Log.v(TAG,tempflag);
						  					
						  					startAnalyze = false;
						  				}
						  				if(current <= drop)
						  				{
						  					showNotification(0, stock, drop_price, current_price, "down");
						  					stockDBAdapter.updateNeedAnalyze(stock,"F");
						  					Message msgneedalarmd = new Message();
						  					msgneedalarmd.what = Globals.STOCK_NEED_ALARM;
						  					sendMessage(msgneedalarmd);
						  					
						  					String tempflag = stockDBAdapter.getNeedAnalyzeFlag(stock);
						  					
						  					Log.v(TAG,tempflag);
						  					
						  					startAnalyze = false;
						  				}
						  				
						  			}
//									try {
//									  		if(isOpenMarketDay()&& isOpenTime())
//									  		{
//									  			Thread.sleep(1000*30);
//									  		}
//									  		else
//									  		{
//									  			startAnalyze = false;
//									  		}
//										} catch (InterruptedException e) {
//											// TODO Auto-generated catch block
//											e.printStackTrace();
//										}
						  			}
						  		}
						  	},"STOCK_NEED_ANALYZE");
					analyzeThread.start();
					}
				}
				else
				{
					startAnalyze = false;
				}
				Log.v(TAG, String.valueOf(flag));
				
				break;
			}
			
			/**
			 * this case used to alarm the user
			 */
			case Globals.STOCK_NEED_ALARM:
			{
				Log.v(TAG,"received need alarm stock!");
				boolean flag = isOpenTime();
				startAnalyze = true;
				
				Message msgneedanalyze = new Message();
				msgneedanalyze.what = Globals.STOCK_NEED_ANALYZE;
				sendMessage(msgneedanalyze);
				
				Log.v(TAG, String.valueOf(flag));
				
				break;
			}
			case Globals.STOCK_FIRST_FRESH:
			{
				Thread t = new Thread(new Runnable() 
			  	  {
				  	@Override
				  	public void run() {
				  		Log.v(TAG,"start first refresh thread!");
				  		if(stockDisplayList != null)
						{
							Message message = Message.obtain();
							message.what= Globals.STOCK_DATABASE_MSG;
							Bundle bundle = new Bundle();
							bundle.putStringArray("", getNowDisplayString());
					
							try{
								message.setData(bundle);
								cMessenger.send(message);
								long date1 = System.currentTimeMillis();
								Log.v(TAG,String.valueOf(date1));
							} catch (RemoteException e)
							{
								e.printStackTrace();
							}
						}
				  		}
				  	},"STOCK_NEED_FIRST_FRESH");
				t.start();
				break;
			}
			case Globals.CAN_NOT_CONNECT_INTERNET:
			{
				Toast.makeText(getApplicationContext(), "Cannot connect the internet!",
                        Toast.LENGTH_SHORT).show();
				closeThread = true;
				break;
			}
			case Globals.STOCK_NEED_FRESH:
			{
				Log.v(TAG,"Fresh the stock from internet!");
				testConnect();
				Thread t = new Thread(new Runnable() 
			  	  {
				  	@Override
				  	public void run() {
				  		Log.v(TAG,"start refresh thread!");
				  		while(!closeThread)
				  		{
				  				Message message = Message.obtain();
				  				Log.v("I'm here ","at the same time!");
				  				Bundle bundle = new Bundle();
				  				if(getURL()!= null)
				  				{
					  				if(Globals.connectmark)
					  				{
						  				Log.v(TAG,getURL());
					  					if(httpConnect(getURL()))
					  					{
					  						message.what= Globals.STOCK_DATABASE_MSG;
					  						bundle.putStringArray("", getNowDisplayString());
					  						try{
					  							message.setData(bundle);
					  							cMessenger.send(message);
					  						} catch (RemoteException e)
					  						{
					  							e.printStackTrace();
					  							closeThread = true;
					  						}
					  					}
					  				}
					  				else
					  				{
					  					Message msgtoself = new Message();
										msgtoself.what = Globals.CAN_NOT_CONNECT_INTERNET;
										mHandler.sendMessage(msgtoself);
					  				}
				  				}
							  	try {
							  		if(isOpenMarketDay()&& isOpenTime())
							  		{
							  			Thread.sleep(1000*60);
							  		}
							  		else
							  		{
							  			Thread.sleep(1000*60*60);
							  		}
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
				  			}
				  		}
				  	},"STOCK_NEED_FRESH");
			t.start();
				Log.v(TAG,"Got need fresh stock code!");
				break;
			}
			case Globals.UIMESSEAGE_CONNECT_OK:
			{
				/*
				 * connect first Check the StockListDB file to find out is there the file? 
				 * if there is ,check the date and decide if it's the latest file
				 * if it is, do nothing
				 * if not, down load the file and make up the new database;
				 */
				String listdate = GetMessage.getListDate(msg);
				Log.v("The listdate is " , listdate);
				try {
					if(FileOperation.makeVersionText())
					{
						Log.v("first"," step!");
						listdate  = listdate.trim();
						if(!listdate.equals(""))
						{
							FileOperation.writeContentString(file_path+"version.txt",listdate);
						}
						else
						{
							Log.v(TAG,"Did not get the listdate!");
						}
						downloadNewFile();
					}
					else
					{
						Cursor search = null;
						search = stockListDB.getAllStockFormatCursor();
						if(search.getCount() == 0)
						{
							Log.v("Hello","It's null!");
							downloadNewFile();
						}
						else
						{
							Log.v("Hello","It has something!");
							search.close();
							listdate  = listdate.trim();
							if(listdate.equals("2011-11-22"))
							{
								stockListDB.open();
								FileOperation.delFile(file_path+"version.txt");
								FileOperation.makeVersionText();
								listdate  = listdate.trim();
								if(!listdate.equals(""))
								{
									FileOperation.writeContentString(file_path+"version.txt",listdate);
								}
								else
								{
									Log.v(TAG,"Did not get the listdate!");
								}
								Log.v(TAG,"Two");
							}
							else if(!listdate.equals(""))
							{
								Log.v(TAG,"Three");
								int version = 2;
								upgradeStockListDB(version);	
							}
						}
						Message msgtoself = new Message();
						msgtoself.what = Globals.STOCK_NEED_FRESH;
						mHandler.sendMessage(msgtoself);
						
						Message msgneedanalyze = new Message();
						msgneedanalyze.what = Globals.STOCK_NEED_ANALYZE;
						sendMessage(msgneedanalyze);
						
						Message msgneedalarm = new Message();
						msgneedalarm.what = Globals.STOCK_NEED_ALARM;
						sendMessage(msgneedalarm);
						
//						Message msgneedrefresh = new Message();
//						msgneedrefresh.what = Globals.STOCK_FIRST_FRESH;
//						mHandler.sendMessage(msgneedrefresh);
						
						
						if(stockDisplayList != null)
						{
							Message message = Message.obtain();
							message.what= Globals.STOCK_DATABASE_MSG;
							Bundle bundle = new Bundle();
							bundle.putStringArray("", getNowDisplayString());
					
							try{
								message.setData(bundle);
								long date1 = System.currentTimeMillis();
								Log.v(TAG,String.valueOf(date1));
								cMessenger.send(message);
							} catch (RemoteException e)
							{
								e.printStackTrace();
							}
						}
						
						
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				//send message
				break;
			}
			case Globals.UIMESSAGE_SEARCH_CODE:
			{
				String code_adds = GetMessage.getAddCode(msg);
				if(findInDB(code_adds))
				{
					Message message = Message.obtain();
					
					message.what = Globals.STOCK_SEARCH_LIST;
					Bundle bundle = new Bundle();
					
					String[] tempArray = new String[stockSearchList.size()*2];
					tempArray = searchedStock();
					bundle.putStringArray(Globals.UINAME_LISTDATE, tempArray);
					
					try {
						message.setData(bundle);
						cMessenger.send(message);
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else if(findInNet(code_adds))
				{
					
				}
				else
				{
					Toast.makeText(RefreshService.this, "Can not find Stock!", Toast.LENGTH_SHORT).show();
				}
				
				break;
			}
			case Globals.UIMESSAGE_ADD_SELECT:
			{
				String code_add = GetMessage.getAddCode(msg);
				if(!isThereTheSameOneSS(code_add))
				{
					Log.v(TAG,"arrivaed here!");
					addNewStock(code_add);
					updateStockList();
					
					//send message
					if(stockDisplayList != null)
					{
						Message message = Message.obtain();
						message.what= Globals.STOCK_DATABASE_MSG;
						Bundle bundle = new Bundle();
						bundle.putStringArray("", getNowDisplayString());
						
						try{
							message.setData(bundle);
							cMessenger.send(message);
						} catch (RemoteException e)
						{
							e.printStackTrace();
						}
					}
					
//					Message msgtoself = new Message();
//					msgtoself.what = Globals.STOCK_NEED_FRESH;
//					sendMessage(msgtoself);
					RefreshStock();
				}
				else
				{
					Message message = Message.obtain();
					message.what= Globals.STOCK_EXIST_MSG;
					Bundle bundle = new Bundle();
					bundle.putStringArray("", tempEmpty);
					try{
						message.setData(bundle);
						cMessenger.send(message);
					} catch (RemoteException e)
					{
						e.printStackTrace();
					}
				}
				break;
			}
			case Globals.UIMESSAGE_ADD_NOTES:
			{
				String remark = GetMessage.getNotes(msg);
				String code_addn = GetMessage.getAddCode(msg);
				Log.v("Remark is ", remark);
				Log.v("Need Add stock is ", code_addn);
				addNotesToStock(code_addn, remark);
				Log.v(TAG,"I add there!");
				break;
			}
			case Globals.UIMESSAGE_SIMULATE_TRADE:
			{
				String code_addn = GetMessage.getAddCode(msg);
				String simnum = GetMessage.getSimulateNumber(msg);
				String simprice = GetMessage.getSimulatePrice(msg);
				String flag = GetMessage.getNumberFlag(msg);
				if(flag.equals("hands"))
				{
					float num = Float.valueOf(simnum)*100;
					simnum = String.valueOf(num);
				}
				
				simulateTrade(code_addn, simnum, simprice);
				
				break;
			}
			case Globals.UIMESSAGE_DELETE_SELECT:
			{
				String code_delete= GetMessage.getAddCode(msg);
				Log.v("Delete Stock is ", code_delete);
				deleteStock(code_delete);
				updateStockList();
				if(stockDisplayList != null)
				{
				Message message = Message.obtain();
				message.what= Globals.STOCK_DATABASE_MSG;
				Bundle bundle = new Bundle();
				bundle.putStringArray("", getNowDisplayString());
				
				try{
						message.setData(bundle);
						cMessenger.send(message);
					} catch (RemoteException e)
					{
						e.printStackTrace();
					}
				}
				break;
			}
			case Globals.UIMESSAGE_STOCK_ALARM:
			{
				String alarm = GetMessage.getAddCode(msg);
				String price_curr = msg.getData().getString(Globals.UINAME_ADD_CODE);
				String price_up = GetMessage.getAlarmUpbound(msg);
				String price_below = GetMessage.getBoboundUpbound(msg);
				String price_up_unit = GetMessage.getUpboundUnit(msg);
				String price_below_unit = GetMessage.getBoboundUnit(msg);
				boolean upvalied = GetMessage.getAlarmUpboundValid(msg);
				boolean bovalied = GetMessage.getAlarmBoboundValid(msg);
				if(upvalied)
				{
					if(price_up_unit.equals("price"))
					{
						Log.v(TAG,"arrived price and updatRisePrice");
						stockDBAdapter.updateRisePrice(alarm,price_up);
					}
					else if(price_up_unit.equals("percent"))
					{
						Log.v(TAG,"arrived price and updatRisePrice");
						stockDBAdapter.updateRisePrice(alarm,calcPercent(price_curr,price_up));		
					}
				}
				if(bovalied)
				{
					if(price_below_unit.equals("price"))
					{	
						stockDBAdapter.updateDropPrice(alarm,price_below);
					}
					else if(price_below_unit.equals("percent"))
					{
						stockDBAdapter.updateDropPrice(alarm,calcPercent(price_curr,price_below));
					}
				}
				if(upvalied || bovalied)
				{
					stockDBAdapter.updateNeedAnalyze(alarm,"T");
					String tempflag = stockDBAdapter.getNeedAnalyzeFlag(alarm);
				
					Log.v(TAG,tempflag);
				
					startAnalyze = true;
				
					Message msgneedanalyze = new Message();
					msgneedanalyze.what = Globals.STOCK_NEED_ANALYZE;
					sendMessage(msgneedanalyze);
				}
				break;
			}
			case Globals.UIMESSAGE_QUIT:
				stopSelf();
				break;
			default:
			{
				super.handleMessage(msg);
			}
			}
		}
		
	};

	protected boolean httpConnect(String stock_url) {
		stock_url = String.format(searchUrl, stock_url);
        if(stock_url != null)
		{
			DefaultHttpClient httpclient_all = new DefaultHttpClient();
			//HttpGet
			HttpGet httpget_all = new HttpGet(stock_url);
			//ResponseHandler
			ResponseHandler<String> responseHandler_all = new BasicResponseHandler();
	    
			try {
				
				String content = httpclient_all.execute(httpget_all, responseHandler_all);
				String[] content_array = content.split("var");
				stockDisplayList.clear();
				Log.v("The arry list length is ",String.valueOf(content_array.length));
				for(i = 1; i < content_array.length; i++)
				{
					tempStockDisplay = getFromContent(content_array[i]);
					tempStockDisplay = new StockDisplay(stockSSCode.get(i-1),tempStockDisplay.getStockName(),tempStockDisplay.getStockNowPrice(),
														tempStockDisplay.getStockRisePrice(),tempStockDisplay.getStockRisePercent());
					/*Add the Date income and other income in the stock display*/
					float temp_simnum = Float.valueOf(stocksimnum.get(stockSSCode.get(i-1)));
					Log.v("Arrived here", "the temp_simnum here!" + String.valueOf(temp_simnum));
					float temp_simprice = Float.valueOf(stocksimprice.get(stockSSCode.get(i-1)));
					float temp_nowprice = Float.valueOf(tempStockDisplay.getStockNowPrice());
					float temp_riseprice = Float.valueOf(tempStockDisplay.getStockRisePrice());
					String dateincome = String.valueOf(temp_simnum*temp_riseprice);
					String sumincome = String.valueOf((temp_nowprice - temp_simprice)*temp_simnum);
					String sumassets = String.valueOf(temp_nowprice*temp_simnum);
					
					
					tempStockDisplay = new StockDisplay(stockSSCode.get(i-1),tempStockDisplay.getStockName(),tempStockDisplay.getStockNowPrice(),
					tempStockDisplay.getStockRisePrice(),tempStockDisplay.getStockRisePercent(), dateincome, sumincome, sumassets);
					stockDBAdapter.updateCurrentPriceCode(stockSSCode.get(i-1), tempStockDisplay.getStockNowPrice());
					stockDisplayList.add(tempStockDisplay);
				} 
			  	} catch (Exception e) {
			  		Log.v(TAG,"Cannot connect the internet!");
			  		Message msgtoself = new Message();
					msgtoself.what = Globals.CAN_NOT_CONNECT_INTERNET;
					mHandler.sendMessage(msgtoself);
			  		return false;
			  	}
			return true;
		}
		else
		{
			Toast.makeText(getApplicationContext(), "No stock to Refresh!",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}
	
	
	private StockDisplay getFromContent(String content) {
		StockDisplay tempStockDisplay;
		tempString = content;
		filter_note = tempString.split("=");
		filter_data = filter_note[1].split("\"");
		s_data = filter_data[1].split(",");
		/*
		 * s_data[0] means stock name
		 * s_data[1] means current_price
		 * s_data[2] means rise price
		 * s_data[3] means rise percent
		 * s_data[4] means deal hands
		 * s_data[5] means deal money(ten thousands)
		 */
		tempStockDisplay = new StockDisplay("",s_data[0],s_data[1],s_data[2],s_data[3]);
		return tempStockDisplay;
	}
	private String getURL() {
		
		String Url = "";
		updateStockList();
		  if(stockSelfSelect.size()!=0){
			  for(i = 0; i < stockSelfSelect.size(); i++)
			  {
				  if(i == 0)
				  {
					  Url += sHead + stockSelfSelect.get(i);
				  }
				  else
				  {
					  Url += (","+ sHead + stockSelfSelect.get(i));
				  }
			  }
		  }
		  else
		  {
			  Url = null;
		  }
		
		return Url;
	}
	
	private void updateStockList() {
//		stockDBAdapter.opened();
		Cursor stockCursor = null;
		stockCursor = stockDBAdapter.getAllStockFormatCursor();
		
		stockCursor.requery();
		
		stockSelfSelect.clear();
		stockSSCode.clear();
		stockDisplayList.clear();
		stocksimnum.clear();
		stocksimprice.clear();
		if(stockCursor != null)
		{
			int count = stockCursor.getCount();
			if(count > 0)
			{
				stockCursor.moveToFirst();
				do {
		  		   		String tmp_search_code = stockCursor.getString(stockCursor.getColumnIndexOrThrow(StockSelfSelectDB.KEY_STOCK_CODE_SEARCH));
		  		   		String tmp_code = stockCursor.getString(stockCursor.getColumnIndexOrThrow(StockSelfSelectDB.KEY_STOCK_CODE)); 
		  		   		String tmp_name = stockCursor.getString(stockCursor.getColumnIndexOrThrow(StockSelfSelectDB.KEY_STOCK_NAME));
		  		   		String tmp_price = stockCursor.getString(stockCursor.getColumnIndexOrThrow(StockSelfSelectDB.KEY_CURRENT_PRICE));
		  		   		String tmp_percent = "+0.00%";
		  		   		String tmp_simnum = stockCursor.getString(stockCursor.getColumnIndexOrThrow(StockSelfSelectDB.KEY_SIMULATE_NUM));
		  		   		String tmp_simprice = stockCursor.getString(stockCursor.getColumnIndexOrThrow(StockSelfSelectDB.KEY_SIMULATE_PRICE));
		  		   		String tmp_datein = "0.00";
		  		   		float price = Float.valueOf(tmp_price);
		  		   		float simprice = Float.valueOf(tmp_simprice);
		  		   		float simnum = Float.valueOf(tmp_simnum);
		  		   		float sumsum = (price - simprice)*simnum;
		  		   		String sumSum = String.valueOf(sumsum);
		  		   		String sumAss = String.valueOf(simnum*price);
		  		   		stocksimnum.put(tmp_code, tmp_simnum);
		  		   		stocksimprice.put(tmp_code, tmp_simprice);
		  		   		stockSelfSelect.add(tmp_search_code);
		  		   		stockSSCode.add(tmp_code);
		  		   		//tempStockDisplay = new StockDisplay(tmp_code, tmp_name, tmp_price, tmp_percent);
		  		   		tempStockDisplay = new StockDisplay(tmp_code, tmp_name, tmp_price, tmp_percent, tmp_datein, sumSum, sumAss);
		  		   		stockDisplayList.add(tempStockDisplay);
		  	   	}while(stockCursor.moveToNext());
			}
			stockCursor.close();
		}
		Log.v(TAG,"first Cursor Leak!");
	}
	
	private String[] getDisplayString() {
		String[] value = new String[stockDisplayList.size()*5];
		for(int j = 0; j < stockDisplayList.size(); j++)
		{
			tempStockDisplay = stockDisplayList.get(j);
			for(i = 5*j; i < 5*(j+1); i++)
			{
				if(i%5 == 0)
				{
					value[i] = tempStockDisplay.getStockCode();
				}
				if(i%5 == 1)
				{
					value[i] = tempStockDisplay.getStockName();
				}
				if(i%5 == 2)
				{
					value[i] = tempStockDisplay.getStockNowPrice();
				}
				if(i%5 == 3)
				{
					value[i] = tempStockDisplay.getStockRisePercent();
				}
				if(i%5 == 4)
				{
					value[i] = tempStockDisplay.getStockRisePrice();
				}
			}
		}
		return value;
	}
	
	private String[] getNowDisplayString() {
		String[] value = new String[stockDisplayList.size()*4];
		
		for(int j = 0; j < stockDisplayList.size(); j++)
		{
			tempStockDisplay = stockDisplayList.get(j);
			for(i = 4*j; i < 4*(j+1); i++)
			{
				if(i%4 == 0)
				{
					value[i] = tempStockDisplay.getStockCode();
				}
				if(i%4 == 1)
				{
					value[i] = tempStockDisplay.getStockName();
				}
				if(i%4 == 2)
				{
					value[i] = tempStockDisplay.getStockNowPrice();
				}
				if(i%4 == 3)
				{
					value[i] = tempStockDisplay.getStockRisePercent();
				}
			}
		}
		return value;
	}
	
	/**
	 * new getdisplay of all the income data
	 */
	private String[] getNowDisplayIncome() {
		String[] value = new String[stockDisplayList.size()*7+3];
		String sumDateIncome;
		String sumSumIncome;
		String sumAssets;
		float sumdate = 0;
		float sumsum = 0;
		float sumass = 0;
		float tempfloat;
		for(int j = 0; j < stockDisplayList.size(); j++)
		{
			tempStockDisplay = stockDisplayList.get(j);
			for(i = 7*j; i < 7*(j+1); i++)
			{
				if(i%7 == 0)
				{
					value[i] = tempStockDisplay.getStockCode();
				}
				if(i%7 == 1)
				{
					value[i] = tempStockDisplay.getStockName();
				}
				if(i%7 == 2)
				{
					value[i] = tempStockDisplay.getStockNowPrice();
				}
				if(i%7 == 3)
				{
					value[i] = tempStockDisplay.getStockRisePercent();
				}
				if(i%7 == 4)
				{
					value[i] = tempStockDisplay.getDateIncome();
					tempfloat = Float.valueOf(value[i]);
					sumdate = sumdate + tempfloat;	
				}
				if(i%7 == 5)
				{
					value[i] = tempStockDisplay.getSumIncome();
					tempfloat = Float.valueOf(value[i]);
					sumsum = sumsum + tempfloat;
				}
				if(i%7 == 6)
				{
					value[i] = tempStockDisplay.getAssets();
					tempfloat = Float.valueOf(value[i]);
					sumass = sumass + tempfloat;
				}
			}
			sumDateIncome = String.valueOf(sumdate);
			value[stockDisplayList.size()*7] = sumDateIncome;
			sumSumIncome = String.valueOf(sumsum);
			value[stockDisplayList.size()*7+1] = sumSumIncome;
			sumAssets = String.valueOf(sumass);
			value[stockDisplayList.size()*7+2] = sumAssets;	
		}
		return value;
	}
	
	/**
	 * add new stock to the database and inform that UI to refresh
	 */
	private void addNewStock(String stockcode) {
		/*
		 * add a new stock like this
		 */
		for(i = 0; i < stockSearchList.size(); i++) 
		{
			Log.v(TAG,stockcode);
			if(stockSearchList.get(i).stock_code.equals(stockcode))
			{
				tempStockFormat = new StockFormat(stockSearchList.get(i).stock_code_search,stockSearchList.get(i).stock_code,stockSearchList.get(i).stock_name);
				stockDBAdapter.insertStock(tempStockFormat);
				Log.v(TAG,stockcode);
				return;
			}
		}
		
		
	}
	
	/**
	 * return a list of stock searched
	 */
	private String[] searchedStock() {
		
		String[] tempArray = new String[stockSearchList.size()*2];
		
		for(i = 0; i < stockSearchList.size(); i++)
		{
			for(int j = i*2; j < 2*(i+1); j++)
			{
				if(j%2 == 0)
				{
					tempArray[j] = stockSearchList.get(i).stock_code;
				}
				if(j%2 == 1)
				{
					tempArray[j] = stockSearchList.get(i).stock_name;
				}
			}
		}
		return tempArray;
	}
	
	/**
	 * delete the stock you chose
	 */
	private void deleteStock(String stockcode) {
		
		stockDBAdapter.removebyStockcode(stockcode);
		
	}
	
	/**
	 * add the stock note to database
	 */
	private void addNotesToStock(String stock_code, String remark) {
		
		stockDBAdapter.updateNotes(stock_code, remark);
		
	}
	
	/**
	 * simulate trade of the stock
	 */
	private void simulateTrade(String stock_code, String simnum, String simprice) {
		
		stockDBAdapter.updateSimulatNum(stock_code, simnum);
		stockDBAdapter.updateSimulatePrice(stock_code, simprice);
		
		
	}
	
	/**
	 * find the selected stock in database first
	 */
	private boolean findInDB(String stockcode) {
		//search in the stockListDB
		Cursor stocklistcursor = null;
		stocklistcursor = stockListDB.getStockCursor(stockcode);
		//clear the stockSearchList
		stockSearchList.clear();
		Log.v(TAG,"Second Cursor Leak!");
		if(stocklistcursor != null)
		{
			if(!stocklistcursor.isAfterLast())
    		{
				for(int i = 0; i < stocklistcursor.getCount(); i++)
				{
					String stock_name = stocklistcursor.getString(stocklistcursor.getColumnIndex(StockListDB.KEY_STOCK_NAME));
					String stock_code = stocklistcursor.getString(stocklistcursor.getColumnIndex(StockListDB.KEY_STOCK_CODE));
					String stock_pinyin = stocklistcursor.getString(stocklistcursor.getColumnIndex(StockListDB.KEY_STOCK_PINYIN));
					String stock_search_code = stocklistcursor.getString(stocklistcursor.getColumnIndex(StockListDB.KEY_STOCK_SEARCH));
					stocklistcursor.moveToNext();
					tempStockSearch = new StockSearch(stock_search_code,stock_name,stock_code,stock_pinyin);
					stockSearchList.add(tempStockSearch);
				}
    		}
			stocklistcursor.close();
			return true;
		}
		else
		{
			return false;
		}
		
	}
	
	/**
	 * find the selected stock in internet second
	 */
	private boolean findInNet(String stock) {
		
		//String parameter
	    //DefaultHttpClient
		long date = System.currentTimeMillis();
		String tmp_url = String.format(searchStock, stock,String.valueOf(date));
		
        if(stock != null)
		{
			DefaultHttpClient httpclient_all = new DefaultHttpClient();
			//HttpGet
			HttpGet httpget_all = new HttpGet(tmp_url);
			//ResponseHandler
			ResponseHandler<String> responseHandler_all = new BasicResponseHandler();
	    
			try {
				
				String content = httpclient_all.execute(httpget_all, responseHandler_all);
				String[] content_array = content.split("var");
				stockDisplayList.clear();
				Log.v("The arry list length is ",String.valueOf(content_array.length));
				for(i = 1; i < content_array.length; i++)
				{
					tempStockDisplay = getFromContent(content_array[i]);
					tempStockDisplay = new StockDisplay(stockSSCode.get(i-1),tempStockDisplay.getStockName(),tempStockDisplay.getStockNowPrice(),
														tempStockDisplay.getStockRisePrice(),tempStockDisplay.getStockRisePercent());
					/*Add the Date income and other income in the stock display*/
					float temp_simnum = Float.valueOf(stocksimnum.get(stockSSCode.get(i-1)));
					float temp_simprice = Float.valueOf(stocksimprice.get(stockSSCode.get(i-1)));
					float temp_nowprice = Float.valueOf(tempStockDisplay.getStockNowPrice());
					float temp_riseprice = Float.valueOf(tempStockDisplay.getStockRisePrice());
					String dateincome = String.valueOf(temp_simnum*temp_riseprice);
					String sumincome = String.valueOf((temp_nowprice - temp_simprice)*temp_simnum);
					String sumassets = String.valueOf(temp_nowprice*temp_simnum);
					
					
					tempStockDisplay = new StockDisplay(stockSSCode.get(i-1),tempStockDisplay.getStockName(),tempStockDisplay.getStockNowPrice(),
					tempStockDisplay.getStockRisePrice(),tempStockDisplay.getStockRisePercent(), dateincome, sumincome, sumassets);
					stockDBAdapter.updateCurrentPriceCode(stockSSCode.get(i-1), tempStockDisplay.getStockNowPrice());
					stockDisplayList.add(tempStockDisplay);
				} 
			  	} catch (Exception e) {
			  		Log.v(TAG,"Cannot connect the internet!");
			  		Message msgtoself = new Message();
					msgtoself.what = Globals.CAN_NOT_CONNECT_INTERNET;
					mHandler.sendMessage(msgtoself);
			  		return false;
			  	}
			return true;
		}
		else
		{
			Toast.makeText(getApplicationContext(), "No stock to Refresh!",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}
	
	/**
	 * show the notification of the alarm and show the correlation of the Activity
	 */
	private void showNotification(int id, String stockcode, String price, String current, String flag) {
    	Intent intent=new Intent(this,SetAlarm.class);
    	intent.putExtra(Globals.UINAME_ALARMINTENT_CODE, stockcode);
    	intent.putExtra(Globals.UINAME_ALARMINTENT_PRICE, price);
    	intent.putExtra(Globals.UINAME_ALARMINTENT_CURRENT, current);
    	intent.putExtra(Globals.UINAME_ALARMINTENT_FLAG, flag);   	
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.stock_alarm_service_started) + " " + stockcode + " arrived " + price + " " + ((flag.equals("up")?"Above":"Below"));

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        intent.setAction(String.valueOf(System.currentTimeMillis()));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.stock_alarm_service_label),
                       text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        
        
        notification.flags|=Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND; 
        mNM.notify(id, notification);
        
    }
	
	/**
	 * calc the percent value and return String
	 */
	private String calcPercent(String currentPrice, String percent) {
		
		float value = Float.valueOf(currentPrice);
		float per = Float.valueOf(percent);
		
		value = (1+per/100)*value;
		BigDecimal a = new BigDecimal(value);
		value = a.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		return String.valueOf(value);
		
	}
	
	/** 
	 * get the file position of the stock list
	 */
	private String getFilePosition() throws IOException {
		
		String dir ="";
		dir = Environment.getExternalStorageDirectory() + "/stocklist/";
		
		File f = new File(dir);
		if(!f.exists())
		{
			f.mkdirs();
		}
		
		String newFileName = urlDownLoad.substring(urlDownLoad.lastIndexOf("/")+1);
		newFileName = dir + newFileName;
		File newFile = new File(newFileName);
		if(!newFile.exists())
		{
			newFile.createNewFile();
		}
		else
		{
			newFile.delete();
			newFile.createNewFile();
		}
		
		return newFileName;
	}
	
	/**
	 * used to download the database file from the internet with one solo thread
	 */
	private void downloadNewFile() {
		
		new Thread(new Runnable () {
			
			public void run() {
				
				try {
					downloadF = System.currentTimeMillis();
					
					String fileName = getFilePosition();
					
					URL myUrl = new URL(urlDownLoad);
					
					URLConnection con = myUrl.openConnection();
					
					InputStream is = con.getInputStream();
					
					byte[] dataBuffer = new byte[1024];
					
					int len;
					
					OutputStream os = new FileOutputStream(fileName);
					
					while((len = is.read(dataBuffer)) != -1)
					{
						os.write(dataBuffer, 0, len);
					}
					
					is.close();
					
					os.close();
					
					downloadFL = System.currentTimeMillis();
					
					Log.v("DownLoad file used time is ",String.valueOf((downloadFL-downloadF)/1000));
					buildStockListDB(file_path+"stocklist.txt");
					
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		},"DOWNLOAD").start();
	}
	
	/**
	 * build up the database of the stocklist
	 */
	private void buildStockListDB(String fileName) {
		
		stockListData.clear();
		dealFile = System.currentTimeMillis();
		File file = new File(fileName);
		String[] tempArray = new String[4];
		for(i = 0; i < 4; i++)
		{
			tempArray[i] = "";
		}
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
			String tempString = null;
			while ((tempString = reader.readLine()) != null){
				StockSearch tempSS = new StockSearch("","","","");
				tempString = tempString.trim();
				tempArray = tempString.split(" ");
				tempSS.stock_code_search = tempArray[0];
				tempSS.stock_name = tempArray[1];
				tempSS.stock_code = tempArray[2];
				tempSS.stock_pinyin = tempArray[3];
				stockListData.add(tempSS);
			}
			
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null){
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		makeDB = System.currentTimeMillis();
		Log.v("Used time is ",String.valueOf((makeDB - dealFile)/1000));
		//stockListDB.closeSynchronous();
		stockListDB.stocklistdb.beginTransaction();
		try
		{
			for(i = 0; i < stockListData.size(); i++)
			{
				tempStockSearch = stockListData.get(i);
				ContentValues newStockList = new ContentValues(); 
			
				newStockList.put(KEY_STOCK_SEARCH, tempStockSearch.getStockSearch());
				newStockList.put(KEY_STOCK_NAME, tempStockSearch.getStockName());
				newStockList.put(KEY_STOCK_CODE, tempStockSearch.getStockCode());
				newStockList.put(KEY_STOCK_PINYIN, tempStockSearch.getStockPinYin());
				//Log.v("insert is ",tempStockSearch.getStockCode());
				stockListDB.stocklistdb.insert("stocklist", null, newStockList);
			}
			stockListDB.stocklistdb.setTransactionSuccessful();
		}
		finally
		{
			stockListDB.stocklistdb.endTransaction();
		}
		makeComp = System.currentTimeMillis();
		Log.v("Used time is ",String.valueOf((makeComp-dealFile)/1000));
	}
	
	/**
	 * upgrade the database of the stocklist
	 */
	
	private void upgradeStockListDB(int version) {
		
		STOCKLISTDB_VERSION = version;
		
		stockListDB = new StockListDB(this);
		
		stockListDB.opened();
    	
    	downloadNewFile();
	}
	/**
	 * to test if there is one already exist in the self selected list
	 */
	private boolean isThereTheSameOneSS(String stockcode) {
		Cursor stocklistcursor = null;
		try{
			stocklistcursor = stockDBAdapter.setCursorToKeyStock(stockcode);
			if(stocklistcursor != null)
			{
				stocklistcursor.close();
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally
		{
			if(stocklistcursor != null)
			{
				stocklistcursor.close();
			}
		}
		return false;
	}
	/**
	 * refresh the stock from internet once
	 */
	public void RefreshStock()
	{
		testConnect();
		Thread t = new Thread(new Runnable() 
	  	  {
		  	@Override
		  	public void run() {
		  		Log.v(TAG,"start refresh thread!");
		  		Message message = Message.obtain();
		  		Log.v("I'm here ","at the same time!");
		  		Bundle bundle = new Bundle();
		  		if(getURL()!= null)
		  		{
				  	Log.v(TAG,getURL());
			  		if(httpConnect(getURL()))
			  		{
			  			message.what= Globals.STOCK_DATABASE_MSG;
			  			bundle.putStringArray("", getNowDisplayString());
			  			try{
			  					message.setData(bundle);
			  					cMessenger.send(message);
			  				} catch (RemoteException e)
			  				{
			  					e.printStackTrace();
			  					closeThread = true;
			  				}
			  			}
		  			}
		  		}
		  	},"STOCK_NEED_FRESH");
		if(Globals.connectmark)
		{
			t.start();
		}
		else
		{
			Message msgtoself = new Message();
			msgtoself.what = Globals.CAN_NOT_CONNECT_INTERNET;
			mHandler.sendMessage(msgtoself);
		}
	}
	/**
	 * find out that which need analyze
	 */
	private void findNeedAnalyzeArray() {
		stockDBAdapter.opened();
		stockNeedAnalyze.clear();
		Cursor stockCursor = null;
		stockCursor = stockDBAdapter.getNeedAnalyzeCursor();
		Log.v(TAG,"Third need find out! Leak!");
		if(stockCursor != null)
		{
			Log.v(TAG,"Arrived here to find out which one need analyze!");
			stockCursor.requery();
			int count = stockCursor.getCount();
			if(count > 0)
			{
				stockCursor.moveToFirst();
				do {
					String tmp_code = stockCursor.getString(stockCursor.getColumnIndex(StockSelfSelectDB.KEY_STOCK_CODE)); 
					String tmp_rise_price = stockCursor.getString(stockCursor.getColumnIndex(StockSelfSelectDB.KEY_RISE_PRICE));
					String tmp_drop_price = stockCursor.getString(stockCursor.getColumnIndex(StockSelfSelectDB.KEY_DROP_PRICE));
					tempStockNeedAnalyze = new StockNeedAnalyze(tmp_code, tmp_rise_price, tmp_drop_price);
					stockNeedAnalyze.add(tempStockNeedAnalyze);
					Log.v(TAG,"HahaHa");
				}while(stockCursor.moveToNext());
			}
			stockCursor.close();
		}
		//Use Local variable Cursor for you program while you will find out so many wired problems
	}
	
	/**
	 * find out is it the right time
	 */
	private boolean isOpenMarketDay() {
		
		Date tempDate = new Date();
		int h;
		Calendar c = Calendar.getInstance();
		c.setTime(tempDate);
		h = c.get(Calendar.DAY_OF_WEEK);
		if(h > 1 && h < 7)
		{
			return true;
		}
		return false;
	}
	
	/**
	 * find out is it the right time
	 */
	private boolean isOpenTime() {
		
		Date a = new Date();
		int hour;
		int min;
		Calendar c = Calendar.getInstance();
		c.setTime(a);
		hour = c.get(Calendar.HOUR_OF_DAY);
		min = c.get(Calendar.MINUTE);
		
		if(hour >= 9 && min >= 30)
		{
			if(hour <= 11 && min <= 30)
			{
				return true;
			}
			
			if(hour >= 13 && min >= 0)
			{
				if(hour <= 15 && min <= 1)
				{
					return true;
				}
			}
			
		}
		
		return false;
	}
	
	/**
	 * Used for always run the service
	 */
	
	void invokeMethod(Method method, Object[] args) {
	    try {
	        method.invoke(this, args);
	    } catch (InvocationTargetException e) {
	        // Should not happen.
	        Log.w("Api", "Unable to invoke method", e);
	    } catch (IllegalAccessException e) {
	        // Should not happen.
	        Log.w("Api", "Unable to invoke method", e);
	    }
	}

	/**
	 * This is a wrapper around the new startForeground method, using the older
	 * APIs if it is not available.
	 */
	void startForegroundCompat(int id, Notification notification) {
	    // If we have the new startForeground API, then use it.
	    if (mStartForeground != null) {
	        mStartForegroundArgs[0] = Integer.valueOf(id);
	        mStartForegroundArgs[1] = notification;
	        invokeMethod(mStartForeground, mStartForegroundArgs);
	        return;
	    }

	    // Fall back on the old API.
	    mSetForegroundArgs[0] = Boolean.TRUE;
	    invokeMethod(mSetForeground, mSetForegroundArgs);
	    mNM.notify(id, notification);
	}

	/**
	 * This is a wrapper around the new stopForeground method, using the older
	 * APIs if it is not available.
	 */
	void stopForegroundCompat(int id) {
	    // If we have the new stopForeground API, then use it.
	    if (mStopForeground != null) {
	        mStopForegroundArgs[0] = Boolean.TRUE;
	        invokeMethod(mStopForeground, mStopForegroundArgs);
	        return;
	    }

	    // Fall back on the old API.  Note to cancel BEFORE changing the
	    // foreground state, since we could be killed at that point.
	    mNM.cancel(id);
	    mSetForegroundArgs[0] = Boolean.FALSE;
	    invokeMethod(mSetForeground, mSetForegroundArgs);
	}


	public void setmNM_fore(NotificationManager mNM_fore) {
		this.mNM_fore = mNM_fore;
	}


	public NotificationManager getmNM_fore() {
		return mNM_fore;
	}
	
	/**
	 * Test if the device connected the internet
	 */
	public void testConnect()
    {
		ConnectivityManager connManager = (ConnectivityManager) this
                            .getSystemService(CONNECTIVITY_SERVICE);
		// 获取代表联网状态的NetWorkInfo对象
		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        // 获取当前的网络连接是否可用
        if (null == networkInfo)
        {
//        	Toast.makeText(this, "NetWork not Available!", Toast.LENGTH_SHORT).show();
            //当网络不可用时，跳转到网络设置页面
            Globals.connectmark = false; 
        } 
        else
        {
        	boolean available = networkInfo.isAvailable();
        	if (available)
        	{
        		Globals.connectmark = true;
        		} 
        	else
        	{
        		Globals.connectmark = false;
        		}
        	}
        }
}
 